const app = getApp()
import { success, fail } from './util.js'
import { apiPrefix, networkErrMsg } from '../config/index.js'

// function post(apiName, data, success, fail, complete) {
//   postShowLoading(apiName, data, "", success, fail, complete)
// }

const requestFailError = res => {
  if (res && res.errMsg && res.errMsg.indexOf('fail failed to connect to') >= 0) {
    fail(networkErrMsg)
  }
  if (res && res.errMsg && res.errMsg.indexOf('request:fail invalid url') >= 0) {
    fail('请求地址不合法')
  }
}

export const fetch = params => {
  params = params || {}
  if (!params.url || !params.url.trim()) {
    return fail('填写请求的url')
  }
  let keys = Object.keys(params)
  let arr = ['success', 'fail', 'complete']
  let hasCb = !!arr.filter(v => { return keys.includes(v) }).length

  let _fail = params.fail
  params.url = apiPrefix + params.url
  if (hasCb) { // 有success或者fail或者complete的执行下面
    params = Object.assign({}, params, {
      fail: res => {
        requestFailError(res)
        _fail && _fail()
      }
    })
    wx.request(params)
  } else { // 没有的话使用Promise
    return new Promise((resolve, reject) => {
      params = Object.assign({}, params, {
        success: res => {
          resolve(res)
        },
        fail: res => {
          requestFailError(res)
          reject(res)
        }
      })
      wx.request(params)
    })
  }
}
